// 路由导航守卫，做权限管理
import router from '@/router'
import store from '@/store'
import getPageTitle from '@/utils/get-page-title'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
const whiteList = ['/login', '/404']
router.beforeEach((to, from, next) => {
  // 设置动态标题
  document.title = getPageTitle(to.meta.title)
  console.log(to.path, '去哪里')
  // console.log(from.path, '从哪里来')
  NProgress.start()
  const token = store.state.user.token
  if (token) {
    // 有token,已登录
    if (to.path === '/login') {
      console.log('已经登录了，不能再登录了，去首页')
      next('/')
      NProgress.done()
    } else {
      console.log('已经登录，去其他页面，放行')
      // 发送ajax请求
      // 判断有没有用户的信息,有就不发，没有就发送请求
      if (!store.state.user.userInfo.userId) {
        store.dispatch('user/setUserInfo')
      }
      next()
    }
    // 没有token,未登录
  } else {
    if (whiteList.includes(to.path)) {
      console.log('拥有白名单，放行')
      next()
    } else {
      console.log('未登录,没有token,去登录页')
      next('/login')
      NProgress.done()
    }
  }
})
router.afterEach(() => {
  NProgress.done()
})
